<template>
  <div class="yy-schedule-setting">
    <el-dialog
        v-model="isVisible"
        title="设置排班计划"
        width="600px"
        :close-on-click-modal="false"
        @close="onCancelDialog"
        :show-close="false"
        class="yy-modal--custom"
    >
      <div style="margin-bottom: 15px;font-size: 16px; display: flex; padding: 10px 10px;
    background: #f1f1f1;">

        <el-select v-model="form.item" placeholder="请选择科目" @change="onSelectItemChange" style="min-width: 120px; flex:1;">
          <el-option :label="item.name" :value="item.id" v-for="item in regItems" :key="item.id"/>
        </el-select>

        <el-select v-if="false" v-model="form.category" placeholder="请选择类别" @change="onSelectCategoryChange" style="min-width: 120px; flex:1;">
          <el-option :label="item.name" :value="item.id" v-for="item in regCategorys" :key="item.id"/>
        </el-select>

      </div>
      <div class="yy-schedule-setting_list">
        <el-calendar>
          <template #date-cell="{ data }">
            <p>
              {{ data.day.split('-').slice(1).join('-') }}
              <el-select :disabled="onDateRender(data.day)" size="small" v-model="scheduleData[getScheduleKey(data.day , form.item,  form.category)]"  placeholder="请选择" style="width:100%;">
                <el-option :label="item.label" :value="item.value" v-for="item in clinicHoursArr" :key="item.value"/>
              </el-select>
            </p>
          </template>
        </el-calendar>
      </div>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="onCancelDialog">关闭</el-button>
          <el-button type="primary" @click="onSave">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>
<script setup lang="ts">
import {reactive, defineEmits, defineProps, defineExpose, ref, onBeforeMount} from "vue";
import {QueueScheduleModel} from "@/model/QueueScheduleModel";
import DoctorClientApi from "@/api/doctor";
import RegCategoryApi from "@/api/queue/RegCategoryApi";
import {QueueRegCategoryModel} from "@/model/QueueRegCategoryModel";
import RegItemApi from "@/api/queue/RegItemApi";
import {QueueRegItemModel} from "@/model/QueueRegItemModel";
import {ElMessage} from "element-plus";

const clinicHoursArr: {label: string, value: number}[] = [
  {label: '休息', value: 0}, {label:'上午', value: 1}, {label: '下午', value: 3}, {label: '全天', value: 5}
]
const $emit = defineEmits({
  'setScheduleSuccess': (schedule) => schedule
})
const isVisible = ref(false)

const regCategorys = ref<QueueRegCategoryModel[]>([])

const regItems = ref<QueueRegItemModel[]>([])

const form = reactive({
  item: '',
  category: ''
})

const emplSchedules = ref()

const currentEmployee = ref()

const currentSchedule = ref<QueueScheduleModel>()
const scheduleData = ref({})
const scheduleMap = ref({})

const onShowDialog = (employee, schedule: QueueScheduleModel) => {
  currentEmployee.value = employee
  currentSchedule.value = schedule

  Promise.all([RegItemApi.listAllRegItem(null, currentEmployee.value.emplId), RegCategoryApi.listRegCategory()])
      .then((res) => {
        if (res) {
          regItems.value = res[0] ? res[0] : []
          if (regItems.value?.length && !form.item) {
            form.item = regItems.value[0].id
          }

          regCategorys.value = res[1] ? res[1] : []
          if (regCategorys.value?.length) {
            form.category = regCategorys.value.find(item => item.categoryFlag === 0).id
          }
        }
        if (!currentSchedule.value) {
          listSchedule()
        }
      })
  if (currentSchedule.value) {
    form.item = currentSchedule.value.itemId
    form.category = currentSchedule.value.categoryId
    listSchedule()
  }

  isVisible.value = true
}

const listDoctorRegItem = () => {
  RegItemApi.listAllRegItem(null, currentEmployee.value.emplId).then((items) => {
    regItems.value = items
    if (items?.length && !form.item) {
      form.item = items[0].id
    }
  })
}

const listRegCategory = () => {
  RegCategoryApi.listRegCategory().then((data) => {
    regCategorys.value = data
    if (data?.length) {
      form.category = data.find(item => item.categoryFlag === 0).id
    }
  })
}

const listSchedule = () => {
  if (form.item && form.category && currentEmployee.value.emplId) {
    DoctorClientApi.listScheduleByEmplId(currentEmployee.value.emplId, form.item, form.category).then(schedules => {
      const obj = {}
      const map = {}
      if (schedules?.length) {
        schedules.forEach((s) => {
          obj[getScheduleKey(s.scheduleDate , s.itemId,  s.categoryId)] = s.clinicHoursId
          map[getScheduleKey(s.scheduleDate , s.itemId,  s.categoryId)] = {
            id: s.id,
            scheduleDate: s.scheduleDate,
            clinicHoursId: s.clinicHoursId
          }
        })
      }
      scheduleData.value = obj
      scheduleMap.value = map
    })
  }
}

const onSelectItemChange = () => {
  scheduleData.value = {}
  listSchedule()
}

const onSelectCategoryChange = () => {
  // listSchedule()
}

const onDateRender = (date) => {
  const yearMonthDateArr = date.split("-");
  const targetDate = new Date(yearMonthDateArr[0], yearMonthDateArr[1] - 1, yearMonthDateArr[2], 23, 59,59);
  const current = new Date()
  const today = new Date(current.getFullYear(), current.getMonth(), current.getDate(), 23, 59, 59)
  return targetDate.getTime() < today.getTime()
}

const onSave = () => {
  const selectItem = regItems.value.find(item => item.id === form.item)
  const selectCategory = regCategorys.value.find(item => item.id === form.category)
  const scheduleList = []
  for(let key in scheduleData.value) {
    if (!scheduleMap.value[key] || scheduleMap.value[key].clinicHoursId != scheduleData.value[key]) {
      const data = new QueueScheduleModel().deserialize(Object.assign({}, {
        id: scheduleMap.value[key]?.id || undefined,
        departId: selectItem.deptId,
        itemId: selectItem.id,
        categoryId: selectCategory.id,
        doctorId: currentEmployee.value.emplId,
        scheduleDate: getScheduleDateFromKey(key),
        clinicHoursId: scheduleData.value[key],
        flowFlag: 1
      }))
      scheduleList.push(data)
    }
  }

  // console.log('------------current schedule list-------------------', scheduleList)
  if (scheduleList.length) {
    DoctorClientApi.scheduleSetting(currentEmployee.value.emplId, scheduleList).then((data) => {
      onCancelDialog()
      // 如果有当前计划
      if (data) {
        $emit('setScheduleSuccess', data)
      }
    })
  } else {
    ElMessage.warning("暂无需要保存的排班!")
  }
}

const getScheduleDateFromKey = (key: string) => {
  if (key.indexOf("_") >= 0) {
     return key.substring(0, key.indexOf("_"))
  }
  return key;
}

const getScheduleKey = (scheduleDate: string, itemId: string, categoryId: string) => {
  return scheduleDate + "_" + itemId + "_" + categoryId
}

const onCancelDialog = () => {
  if (isVisible.value) {
    setTimeout(() => {

    }, 200)
  }
  isVisible.value = false
}

defineExpose({
  onShowDialog
})

</script>
<style scoped lang="scss">
.yy-schedule-setting_list {
  &-item {
    display: flex;
    & > div:nth-child(1) {
      flex: 2;
    }
    & > div:nth-child(2) {
      flex: 1;
    }
    & > div:nth-child(3) {
      justify-content: flex-end;
      flex: 1;
    }
    & > div {
      display: inline-flex;
      align-items: center;
      padding: 5px 10px;
    }
  }
}
:deep(.el-calendar__body) {
  padding:5px 10px 0px;
}
:deep(.el-calendar__header) {
  padding: 5px 10px;
}
:deep(.el-calendar-table thead th) {
  padding: 3px 0;
}
:deep(.el-calendar-table .el-calendar-day) {
  height: auto;
  padding: 4px;
}
</style>
